package com.cloudeasy.file.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件工具类
 */
@Slf4j
public class FileUtil {
    /**
     * 构建文件名
     *
     * @param fileName 原始文件名
     * @return 构建的文件名
     */
    public static String buildName(String fileName) {
        return System.currentTimeMillis() + "-" + fileName;
    }

    /**
     * 保存文件
     *
     * @param file {@link MultipartFile}
     * @param path 路径
     * @return 保存文件名
     */
    public static String save(MultipartFile file, String path) {
        // 生成新的文件名
        String fileName = buildName(file.getOriginalFilename());
        String targetFileName = path + "/" + fileName;

        File target = new File(targetFileName);

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), target);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    /**
     * 写出文件
     *
     * @param path     文件路径
     * @param response {@link HttpServletResponse}
     */
    public static void get(String path, HttpServletResponse response) {
        File file = new File(path);
        if (file.exists()) {
            try (FileInputStream fileInputStream = FileUtils.openInputStream(file);
                 ServletOutputStream outputStream = response.getOutputStream()) {
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
